<?php
/**
 * 生成CRETE TABLE 语句
 *
 * @access  public
 * @param   
 *
 * @return void
 */
function get_table_df($table, &$sql)
{
	
	$sql_create = "";
	$field_query = "SHOW FIELDS FROM $table";
	$key_query = "SHOW KEYS FROM $table";

 	$sql_create .= "\nDROP TABLE IF EXISTS $table;\n";	

    $sql_create .= "-- \n-- 表的結搆 `$table` \n--\n";
	$sql_create .= "CREATE TABLE `$table` (\n";


   	$rs = mysql_query($field_query);
	if(! $rs)
	{
        echo mysql_error();
        return FALSE;
	}

	while ($row = mysql_fetch_array($rs))
	{
		$sql_create .= '   `' . $row['Field'] . '` ' . $row['Type'];

		if(!empty($row['Default']))
		{
			$sql_create .= ' DEFAULT \'' . $row['Default'] . '\'';
		}

		if($row['Null'] != "YES")
		{
			$sql_create .= ' NOT NULL';
		}

		if($row['Extra'] != "")
		{
			$sql_create .= ' ' . $row['Extra'];
		}

		$sql_create .= " ,\n";
	}

    /* 清除最后一个$crlf */
	$sql_create = ereg_replace(',$', "", $sql_create);

    /* 設置索引 */

	$rs = mysql_query($key_query);
	if(!$rs)
	{
        die(mysql_error());
        return FALSE;
	}
    $index = array();
	while($row = mysql_fetch_array($rs))
	{
		$kname = $row['Key_name'];

		if(($kname != 'PRIMARY') && ($row['Non_unique'] == 0))
		{
			$kname = "UNIQUE|$kname";
		}

		if(!is_array($index[$kname]))
		{
			$index[$kname] = array();
		}

		$index[$kname][] = $row['Column_name'];
	}

	while(list($x, $columns) = @each($index))
	{
		$sql_create .= "";

		if($x == 'PRIMARY')
		{
			$sql_create .= '  PRIMARY KEY (' . implode($columns, ', ') . ')';
		}
		elseif (substr($x,0,6) == 'UNIQUE')
		{
			$sql_create .= '  UNIQUE ' . substr($x,7) . ' (' . implode($columns, ', ') . ')';
		}
		else
		{
			$sql_create .= "  KEY $x (" . implode($columns, ', ') . ')';
		}
	}

	$sql_create .= "\n);\n";

	if(get_magic_quotes_runtime())
	{
        $sql .= stripslashes($sql_create);
        return true;
	}
	else
	{
        $sql .= $sql_create;
		return true;
	}
}

/**
 * 生成INSERT 语句
 *
 * @access  public
 * @param   
 *
 * @return void
 */
function get_table_content($table, &$sql,$mark)
{
    $trans = array("\n"=>'\n\r', "'"=>"''" );
    
	/* 获取数据表数据 */
    $content_query = "SELECT * FROM $table";
	if (! ($ret = mysql_query($content_query)))
	{
        die(mysql_error());
        return FALSE;
	}

	/* 创建数据插入语句 */
    $tag = true;
    $is_first = 1;
	while ($row = mysql_fetch_array($ret))
	{
        $sql_insert = '';
        if ($tag)
        {
            $keys = array_keys($row);
            $field_name = array();
            for($i=1 ; $i<count($keys); $i+=2)
            {
                $field_names[] = $keys[$i];
            }
            $table_list = implode('`,`',$field_names);
            $table_list = '( `'.$table_list . '`)';

            $tag = false;
        }
        
        $values = array();
        for($i=0 ; $i<count($row)/2; $i++)
        {
            $values[] = strtr($row[$i],$trans);
        }
        
        $field_values = implode('\', \'', $values);
        $field_values = '( \''.$field_values.'\' )';
        if ($mark)
        {
            if ($is_first == 1)
            {
                $sql_insert = "INSERT INTO `$table` $table_list VALUES $field_values ;\n";
                $is_first ++;
                
            }
            else
            {
                $sql_insert = $field_values.";\n";
            }
        } 
        else
        {
            $sql_insert = "INSERT INTO `$table` $table_list VALUES $field_values ;\n";
        }

        $sql .= $sql_insert ;
     

	}
	return  true;
}

/**
 * 获取数据库中所有的表名
 *
 * @param  string $dbName  数据库名称
 * @param  string $tbl_pre 表名前缀
 * @return array  表名
 */
 function getTables($dbName, $tbl_pre='')
 {
   $result = mysql_list_tables($dbName);
   if (! $result) 
   {	
      echo ('打開數據庫錯誤 Mysql:') . mysql_error();
	  exit(0);
   }
   $tbl_pre_len = strlen($tbl_pre);  //表名前缀长度
   while ($row = mysql_fetch_row($result)) 
   {
      $tbl_name = $row[0];
	  if ($tbl_pre_len)
	    if (substr($tbl_name, 0, $tbl_pre_len) != $tbl_pre)
          continue ;
      $Tables[] = $tbl_name;
   }
   mysql_free_result($result);	
   return $Tables;
 }

/**
 * 
 *
 * @access  public
 * @param   
 *
 * @return void
 */
function import($sql_file)
{
    $sql_str    = str_replace("\r", '', implode('', file($sql_file)));
    $ret        = explode(";\n", $sql_str);    

    /* 执行sql语句 */
    for ($i=0; $i<count($ret); $i++)
    {
        $ret[$i] = stripslashes(trim($ret[$i]));
        if(! empty($ret[$i]))
        {

            if(! mysql_query($ret[$i]))
            {              
 
                return false;
            }
           
        }
    }

    return true;
}


/**
 * 将字节转成可阅读格式
 *
 * @access  public
 * @param   
 *
 * @return void
 */
function num_bitunit($num){
  $bitunit=array(' B',' KB',' MB',' GB');
  for($key=0;$key<count($bitunit);$key++){
	if($num>=pow(2,10*$key)-1){ //1023B 会显示为 1KB
	  $num_bitunit_str=(ceil($num/pow(2,10*$key)*100)/100)." $bitunit[$key]";
	}
  }
  return $num_bitunit_str;
}
?>